﻿define(['services/logger', 'durandal/app', './createAlbum', 'plugins/dialog', 'plugins/router'], function (logger, app, createAlbumView, dialog, router) {

    var title = 'Home';

    //Album child router
    var childRouter = router.createChildRouter();
    childRouter.makeRelative({
        moduleId: 'viewmodels/home',
        fromParent: true
    }).map([
            { route: 'albums/:id', moduleId: 'albums/index', title: 'Photo', type: 'intro', nav: false },
    ]).buildNavigationModel();

    // Command Structure observable
    function Album(data) {

        this.IsActive = ko.observable(false);

        this.AlbumId = ko.observable(data.AlbumId);
        this.Name = ko.observable(data.Name);
        this.Description = ko.observable(data.Description);
        this.IsEnabled = ko.observable(data.IsEnabled);
        this.Photos = ko.observable(data.Photos);
        this.CreatedOn = ko.observable(data.CreatedOn);
        this.ModifiedOn = ko.observable(data.ModifiedOn);
    };

    function EmptyAlbum() {
        this.AlbumId = ko.observable(0);
        this.Name = ko.observable('');
        this.Description = ko.observable('');
        this.IsEnabled = ko.observable(true);
        this.Photos = ko.observable(null);
        this.CreatedOn = ko.observable();
        this.ModifiedOn = ko.observable();
    };
    //View model observable
    var albums = ko.observableArray([]);

    //View model
    var vm = {
        router: childRouter,
        activate: activate,
        attached: attached,
        title: title,
        selectedAlbums: ko.observable(null),
        albums: albums,
        selectionChanged: selectionChanged,
        createAlbumModal: createAlbumModal,
        updateAlbumModal: updateAlbumModal,
        deleteAlbumModal: deleteAlbumModal,

        page: ko.observable(0),
    };

    return vm;

    //#region Internal Methods
    function attached(view, parent) {
        var maxWidth = $(window).width();
        //$('#splitter').width(maxWidth);
        //$('#splitter').split({ orientation: 'vertical', limit: 120, position: '20%' });
    }

    function activate(fromChild) {
        if (albums().length > 0) {
            return true;
        }
        else {
            //logger.log(title + ' View Activated', null, title, true);
            var uri = '/api/1.0/Album';
            var promise = $.getJSON(uri).done(function (data) {
                // On success, 'data' contains a list of products.
                var results = $.map(data, function (item) {
                    return new Album(item)
                });
                albums(results);
            });
            return promise; 
        }
    }

    function selectionChanged(item, parent) {

        router.navigate('#home/albums/' + item.AlbumId());
        
        $.each(this.albums(), function(index, value) {
            value.IsActive(false);
        });

        item.IsActive(true);
    }

    function createAlbumModal() {
        createAlbumView.show(new EmptyAlbum()).then(function (data) {
            if (data != null)
            {
                var uri = '/api/1.0/Album';
                $.ajax({
                    url: uri,
                    type: 'POST',
                    data: ko.toJSON(data),
                    contentType: "application/json;charset=utf-8",
                    success: function (data) {
                        var results = new Album(data);
                        albums.push(results);
                    },
                    error: function (x, y, z) {
                        alert(x + '\n' + y + '\n' + z);
                    }
                });
            }
        });
    }

    function deleteAlbumModal(item) {
        dialog.showMessage('Suppression complète de l\'album?', 'Just Checking...', ['Yes', 'No'])
              .then(function(dialogResult){
                  if (dialogResult == 'Yes')
                  {
                      var uri = '/api/1.0/Album' + '/' + item.AlbumId();
                      $.ajax({
                          url: uri,
                          type: 'DELETE',
                          contentType: "application/json;charset=utf-8",
                          success: function (data) {
                              albums.remove(item);
                          },
                          error: function (x, y, z) {
                              alert(x + '\n' + y + '\n' + z);
                          }
                      });
                  }
              });
    }

    function updateAlbumModal(item) {
        createAlbumView.show(item).then(function (data) {
            if (data != null) {
                var uri = '/api/1.0/Album' + '/' + data().AlbumId();

                $.ajax({
                    url: uri,
                    type: 'PUT',
                    data: ko.toJSON(data),
                    contentType: "application/json;charset=utf-8",
                    success: function (data) {
                        var a = 0;
                        
                    },
                    error: function (x, y, z) {
                        alert(x + '\n' + y + '\n' + z);
                    }
                });
            }
        });
    }

    function arrayObjectIndexOf(myArray, searchTerm, property) {
        for (var i = 0, len = myArray.length; i < len; i++) {
            if (myArray[i][property] === searchTerm) return i;
        }
        return -1;
    }



    //#endregion

   

    //region Extension method
    Array.prototype.unset = function (index) {
        if (index > -1) {
            this.splice(index, 1)
        }
    }
    //#endregion Extension Method

});